<template>
    <div>
        <div class="game-img-wrap">
            <div class="left-game-img" v-show="gameImgShow">
                <div class="material-title">
                    <span>游戏详情展示图</span>
                </div>
                <div class="game-cut-img-box"
                    v-loading="gameImgLoading">
                    <img v-if="gameImg" :src="gameImg" alt="" class="img-box">
                    <img v-else src="./img/1440.png" alt="" class="img-box">
                    <div class="wrap-img-box">
                        <div class="main-top-box-1440"><span>重要文字或内容避开此区域</span></div>
                        <div class="tools">
                            <i class="el-icon-search" @click="searchImg('gameImg')"></i>
                            <i class="el-icon-folder-opened" @click="$refs.gameImgInput.click()">
                                <input type="file" ref="gameImgInput" @change="imgInput($event, 'gameImg')" class="input-file" accept=".jpg,.jpeg,.png">
                            </i>
                            <template v-if="gameImg">
                                <i class="el-icon-view" @click="showImg(gameImg)"></i>
                                <i class="el-icon-scissors" @click="editImg('gameImg')"></i>
                                <i class="el-icon-delete" @click="delImg('gameImg')"></i>
                            </template>
                        </div>
                        <div class="main-bottom-box-1440"><span>重要文字或内容避开此区域</span></div>
                    </div>
                </div>
            </div>

            <div class="right-game-img">
                <div class="material-title" v-if="bannerTitleShow">
                    <span>{{ bannerText }}</span>
                </div>
                <div class="game-cut-img-box" :class="{'lottery-banner-box': imgWidth}"
                    v-loading="bannerImgLoading">
                    <img v-if="bannerImg" :src="bannerImg" alt="" class="img-box">
                    <img v-else src="./img/528.png" alt="" class="img-box" :class="{'lottery-img-box': imgWidth}">
                    <div class="wrap-img-box">
                        <div class="tools">
                            <i class="el-icon-search" @click="searchImg('bannerImg')"></i>
                            <i class="el-icon-folder-opened" @click="$refs.bannerImgInput.click()">
                                <input type="file" ref="bannerImgInput" @change="imgInput($event, 'bannerImg')" class="input-file" accept=".jpg,.jpeg,.png">
                            </i>
                            <template v-if="bannerImg">
                                <i class="el-icon-view" @click="showImg(bannerImg)"></i>
                                <i class="el-icon-scissors" @click="editImg('bannerImg')"></i>
                                <i class="el-icon-delete" @click="delImg('bannerImg')"></i>
                            </template>
                        </div>
                        <div class="main-bottom-box-528" v-if="bannerHintShow"><span>重要文字或内容避开此区域</span></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑图片 -->
        <el-dialog
            title="编辑图片"
            class="drap-dialog-box"
            :visible.sync="showImgEdit"
            :show-close="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="90%">
            <div class="desc-text">注：如裁剪框小于{{option.width * enlarge}} x {{option.height * enlarge}}，说明所上传图片尺寸不符和要求，建议 <b>更换图片</b> 或 <b>原图上传</b></div>
            <div class="drap-box" v-if="showImgEdit">
                <div v-if="type === 'gameImg' && showWrap" class="cut-wrap-1440-top" :style="{width: option.width + 'px'}">
                    <span>重要文字或内容避开此区域</span>
                </div>
                <div v-if="type === 'gameImg' && showWrap" class="cut-wrap-1440-bottom" :style="{width: option.width + 'px'}">
                    <span>重要文字或内容避开此区域</span>
                </div>
                <div v-if="type === 'bannerImg' && showWrap" class="cut-wrap-528-bottom" :style="{width: option.width + 'px'}">
                    <span>重要文字或内容避开此区域</span>
                </div>
                <vueCropper
                    class="cropper-box"
                    ref="cropper"
                    :img="option.img"
                    :autoCropWidth="option.width"
                    :autoCropHeight="option.height"
                    :outputSize="1"
                    :fixedBox="true"
                    :autoCrop="true"
                    :centerBox="true"
                    :infoTrue="true"
                    :canMoveBox="false"
                    :enlarge="enlarge"
                >
                </vueCropper>
            </div>

            <div slot="footer" class="dialog-footer">
                <div class="wrap-flag">
                    <span>显示最佳展示区</span>
                    <el-switch
                    v-model="showWrap">
                    </el-switch>
                </div>
                <div class="all-btn-box">
                    <el-button @click="cancleUploadImg">取 消</el-button>
                    <el-button type="primary" @click="cutImg">确 定</el-button>
                    <el-button v-if="newImg" type="success" @click="noCutImg">不裁剪原图上传</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 图片预览 -->
        <div
            v-if="isShowImg"
            @click="isShowImg = false"
            class="drap-show-img-box">
            <div class="img-box">
                <img :src="currentImg" alt="">
            </div>
        </div>

        <!-- 百度搜索相关 -->
        <el-dialog
            title="百度搜图"
            class="baidu-search-box"
            :visible.sync="showBaiduSearch"
            width="90%">
            <div class="baidu-box" ref="baiduBox">
                <div class="search-box">
                    <el-input v-model.trim="baiduSearchKeyWord" @keyup.enter.native="resetBaiduSearch" style="width:400px" clearable></el-input>
                    <div class="baidu-btn" @click="resetBaiduSearch">百度一下</div>
                </div>
                <ul class="baidu-img-list-box" :infinite-scroll-disabled="baiduNoMore || baiduLoading " v-if="baiduImgList && baiduImgList.length" v-infinite-scroll="baiduSearch" style="overflow:auto">
                    <li v-for="(item, index) in baiduImgList" class="baidu-img-list-item"  @click="checkBaiduImg(item)" :key="index" :class="{'no-show-img': !item._height, 'img-checked': item.isCheck}">
                        <img :src="item.middleURL" alt="" :style="{height: item._height + 'px', width: item._width + 'px', backgroundColor: item._bgc}">
                        <div class="hover-box">{{item.width}} x {{item.height}}</div>
                        <div class="check-box"></div>
                    </li>
                    <li class="baidu-center" v-if="baiduNoMore">没有更多了~</li>
                    <li v-if="baiduLoading" class="baidu-center">加载中...</li>
                </ul>
                <div class="baidu-center" v-else-if="baiduNoMore">没有更多了~</div>
                <div class="no-baidu-img" v-else>输入搜索条件后查询~</div>
            </div>

            <div class="baidu-btn-box" v-if="baiduImgCheckList && baiduImgCheckList.length">
                <el-button type="info" @click="cancleChecked">取消选中</el-button>
                <el-button type="primary" @click="addToWarehouse">{{type === 'gameImg' ? '添加到游戏详情展示图' : '游戏banner'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
    data () {
        return {
            option: {
                img: '',
                width: 270,
                height: 360
            }, // 裁剪参数
            gameImg: '',
            bannerImg: '',
            gameImgLoading: false,
            bannerImgLoading: false,
            isShowImg: false, // 是否预览图片
            currentImg: '', // 要预览的图片
            showImgEdit: false, // 显示编辑弹窗
            newImg: false, // 是否是新上传的图片
            type: '', // 当前编辑某张图片
            files: null, // 上传的文件
            // 百度搜索相关
            showBaiduSearch: false, // 百度搜图
            baiduSearchKeyWord: '', // 百度搜图关键字
            baiduImgList: [], // 百度查询结果图片
            baiduNoMore: false,
            baiduLoading: false,
            baiduPageNum: 0,
            scaleList: [], // 总比例数组
            rowScale: 0, // 一行总比例计数
            baiduImgCheckList: [], // 百度选中的图片
            showWrap: true, // 是否显示裁剪遮罩
            enlarge: 3 // 裁剪框图片生成比例
        }
    },

    props: {
        cover: {
            type: String,
            default: ''
        },
        banner: {
            type: String,
            default: ''
        },
        imgWidth: {
            type: String,
            default: ''
        },
        imgHeight: {
            type: String,
            default: ''
        },
        bannerText: {
            type: String,
            default: '游戏banner'
        },
        gameImgShow: {
            type: Boolean,
            default: true
        },
        bannerTitleShow: {
            type: Boolean,
            default: true
        },
        bannerHintShow: {
            type: Boolean,
            default: true
        }
    },

    created () {
        this.gameImg = this.cover || ''
        this.bannerImg = this.banner || ''
    },

    watch: {
        cover (val) {
            this.gameImg = val
        },

        banner (val) {
            this.bannerImg = val
        },

        gameImg (val) {
            this.$emit('updateImg', val, 'gameImg')
        },

        bannerImg (val) {
            this.$emit('updateImg', val, 'bannerImg')
        }
    },

    methods: {
        // 查看图片
        showImg (url) {
            this.currentImg = url
            this.isShowImg = true
        },

        // 上传图片
        imgInput (e, type) {
            this.type = type
            if (type === 'gameImg') {
                this.option.width = 1080 / 3
                this.option.height = 1440 / 3
                this.enlarge = 3
            } else if (type === 'bannerImg') {
                if (this.imgWidth && this.imgHeight) {
                    this.option.width = this.imgWidth / 2
                    this.option.height = this.imgHeight / 2
                } else {
                    this.option.width = 1080 / 2
                    this.option.height = 528 / 2
                    this.enlarge = 2
                }
            }
            this.files = e.target.files[0]
            let reader = new FileReader()
            reader.readAsDataURL(this.files)
            reader.onloadend = () => {
                this.option.img = reader.result
                // 新上传的图片 展示直接上传按钮
                this.newImg = true
                this.showImgEdit = true
            }
        },

        // 编辑图片
        editImg (type) {
            // 记录当前编辑的图片
            this.type = type
            if (type === 'gameImg') {
                this.option.img = this.gameImg
                this.option.width = 1080 / 3
                this.option.height = 1440 / 3
                this.enlarge = 3
            } else if (type === 'bannerImg') {
                if (this.imgWidth && this.imgHeight) {
                    this.option.width = this.imgWidth / 2
                    this.option.height = this.imgHeight / 2
                } else {
                    this.option.img = this.bannerImg
                    this.option.width = 1080 / 2
                    this.option.height = 528 / 2
                    this.enlarge = 2
                }
            }
            // 不是新上传的图片 不展示直接上传按钮
            this.newImg = false
            this.showImgEdit = true
        },

        // 取消编辑
        cancleUploadImg () {
            this.showImgEdit = false
            this.$refs.gameImgInput.value = null
            this.$refs.bannerImgInput.value = null
        },

        // 裁剪图片
        cutImg () {
            this.$refs.cropper.getCropBlob((data) => {
                this.files = data
                if (this.type === 'gameImg') {
                    this.gameImgLoading = true
                } else if (this.type === 'bannerImg') {
                    this.bannerImgLoading = true
                }
                this.uploadImg()
            })
        },

        // 上传图片
        async uploadImg () {
            this.showImgEdit = false
            let files = this.files
            if (!files) return
            let formData = new FormData()
            formData.append('file', files)
            formData.append('needTransform', 1)
            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            let res = await this.$http.post('/file/uploadPic', formData, config)
            if (res.code === '0') {
                if (this.type === 'gameImg') {
                    this.$emit('updateImg', res.data, this.type)
                } else if (this.type === 'bannerImg') {
                    this.$emit('updateImg', res.data, this.type)
                }
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
            this.gameImgLoading = false
            this.bannerImgLoading = false
            this.files = null
        },

        // url上传
        async urlUploadImg (url) {
            // url = url.replace('http://', 'https://')
            try {
                let res = await this.$http.get('/file/uploadPicByUrl', {
                    params: {
                        url
                    }
                })
                if (res.code === '0') {
                    if (this.type === 'gameImg') {
                        this.$emit('updateImg', res.data, this.type)
                    } else if (this.type === 'bannerImg') {
                        this.$emit('updateImg', res.data, this.type)
                    }
                } else {
                    this.$message({
                        type: 'error',
                        message: res.desc
                    })
                }
                this.gameImgLoading = false
                this.bannerImgLoading = false
            } catch (error) {
                this.$message({
                    type: 'error',
                    message: '图片获取失败，请稍后再试~'
                })
                this.gameImgLoading = false
                this.bannerImgLoading = false
            }
        },

        // 原图上传
        noCutImg () {
            if (this.type === 'gameImg') {
                this.gameImgLoading = true
            } else if (this.type === 'bannerImg') {
                this.bannerImgLoading = true
            }
            this.uploadImg()
        },

        // 删除图片
        delImg (type) {
            if (type === 'gameImg') {
                this.$emit('updateImg', '', type)
            } else if (type === 'bannerImg') {
                this.$emit('updateImg', '', type)
            }
        },

        // 百度搜索相关
        // 打开百度搜图弹窗
        searchImg (type) {
            this.type = type
            this.showBaiduSearch = true
        },

        // 重新查图
        resetBaiduSearch () {
            // 重置相关参数
            // 计数
            this.baiduPageNum = 0
            // 计算一行图片数组
            this.scaleList = []
            // 一行计算总数
            this.rowScale = 0
            // 清空总图片
            this.baiduImgList = []
            // 选中图片
            this.baiduImgCheckList = []
            this.baiduNoMore = false
            this.baiduSearch()
        },

        // 百度搜图接口
        async baiduSearch (e) {
            let width = this.$refs.baiduBox.clientWidth - 20
            if (!this.baiduSearchKeyWord) {
                this.$message({
                    type: 'info',
                    message: '请输入查询条件~'
                })
                return
            }
            this.baiduLoading = true
            this.baiduPageNum++
            let res = await this.$http.get('/task/getImage', {
                params: {
                    keyword: this.baiduSearchKeyWord,
                    pageNum: this.baiduPageNum,
                    pageSize: 30
                }
            })
            if (res.code === '0' && res.data && res.data.length) {
                res.data.forEach(item => {
                    // 单个图片比例
                    item._scale = item.width / item.height
                    // 总比例累计
                    this.rowScale += item._scale

                    item.isCheck = false
                    // 总比例数组累计元素
                    this.scaleList.push(item)
                    if (this.rowScale >= 6) {
                        let _width = width - (this.scaleList.length - 1) * 6
                        this.scaleList.forEach(_item => {
                            _item._height = _width / this.rowScale
                            _item._width = _item._scale * _item._height
                            let _random = Math.random() * 255
                            _item._bgc = `rgb(${_random}, ${_random}, ${_random})`
                        })
                        this.scaleList = []
                        this.rowScale = 0
                    }
                })
                this.baiduImgList.push(...res.data)
            } else {
                this.baiduNoMore = true
            }
            this.baiduLoading = false
        },

        // 选中、取消 单个图片
        checkBaiduImg (item) {
            item.isCheck = !item.isCheck
            this.baiduImgCheckList.forEach(item => {
                item.isCheck = false
            })
            this.baiduImgCheckList = []
            if (item.isCheck) {
                this.baiduImgCheckList.push(item)
            }
        },

        // 取消选中
        cancleChecked () {
            // 清空选中
            this.baiduImgCheckList.forEach(item => {
                item.isCheck = false
            })
            // 清空选中数组
            this.baiduImgCheckList = []
            this.showBaiduSearch = false
        },

        // 添加到素材库
        addToWarehouse () {
            let [item] = this.baiduImgCheckList
            if (this.type === 'gameImg') {
                this.gameImgLoading = true
            } else if (this.type === 'bannerImg') {
                this.bannerImgLoading = true
            }
            this.urlUploadImg(item.thumbURL)
            this.cancleChecked()
        }
    },

    components: {
        VueCropper
    }
}
</script>

<style lang="scss" scoped>
    .game-img-wrap {
        display: flex;
        .left-game-img {
            .game-cut-img-box {
                width: 270px;
                height: 360px;
            }
        }

        .right-game-img {
            margin-left: 10px;
            .game-cut-img-box {
                width: 270px;
                height: 132px;
            }
            .lottery-banner-box {
                width: 360px;
                height: 210px;
            }
        }

        .material-title {
            font-size: 14px;
            font-weight: 500;
            padding-bottom: 5px;
        }

        .game-cut-img-box {
            position: relative;
            top: 0;
            left: 0;
            z-index: 1;
            &:hover {
                .wrap-img-box {
                    display: block;
                }
            }
            .img-box {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
            .lottery-img-box {
                object-fit: inherit;
            }
            .wrap-img-box {
                display: none;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 1;
                width: 100%;
                height: 100%;
                color: #ffffff;
                font-size: 20px;
                background-color: rgba(0, 0, 0, .3);
                .tools {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: space-around;
                    > i {
                        position: relative;
                        cursor: pointer;
                        .input-file {
                            position: absolute;
                            top: 0;
                            left: 0;
                            z-index: 1;
                            display: none;
                            width: 20px;
                            height: 21px;
                        }
                    }
                }
                .main-top-box-1440 {
                    top: 0;
                    height: 48px;
                }
                .main-bottom-box-1440 {
                    bottom: 0;
                    height: 94px;
                }
                .main-bottom-box-528 {
                    bottom: 0;
                    height: 32px;
                }
                .main-bottom-box-528, .main-top-box-1440, .main-bottom-box-1440 {
                    position: absolute;
                    left: 0;
                    z-index: 1;
                    width: 100%;
                    background-color: rgba(187,0,0, .6);
                    font-size: 16px;
                    color: #ffffff;
                    text-align: center;
                    > span {
                        position: absolute;
                        width: 100%;
                        top: 50%;
                        left: 50%;
                        z-index: 1;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }

    // 编辑图片
    .drap-dialog-box {
        /deep/ .el-dialog__body {
            padding: 0 20px;
        }
        .el-dialog {
            margin-top: 50px;
        }
        .el-dialog__body {
            padding: 0 20px;
        }
        .desc-text {
            font-weight: normal;
        }
        .drap-box {
            // margin-top: 20px;
            position: relative;
            top: 0;
            left: 0;
            z-index: 1;
            height: 500px;
            .cropper-box {
                height: 500px;
            }
            .cut-wrap-1440-top {
                position: absolute;
                top: 50%;
                left: 50%;
                z-index: 1;
                height: 64px;
                transform: translate(-50%, -240px);
                background-color: rgba(187, 0, 0, 0.6);
            }
            .cut-wrap-1440-bottom {
                position: absolute;
                bottom: 50%;
                left: 50%;
                z-index: 1;
                height: 125.3px;
                transform: translate(-50%, 240px);
                background-color: rgba(187, 0, 0, 0.6);
            }
            .cut-wrap-528-bottom {
                position: absolute;
                bottom: 50%;
                left: 50%;
                z-index: 1;
                height: 64px;
                transform: translate(-50%, 132px);
                background-color: rgba(187, 0, 0, 0.6);
            }
            .cut-wrap-1440-top, .cut-wrap-1440-bottom, .cut-wrap-528-bottom {
                font-size: 16px;
                color: #ffffff;
                text-align: center;
                > span {
                    position: absolute;
                    width: 100%;
                    top: 50%;
                    left: 50%;
                    z-index: 1;
                    transform: translate(-50%, -50%);
                }
            }
        }

        .dialog-footer {
            display: flex;
            justify-content: space-between;
            .wrap-flag {
                display: flex;
                align-items: center;
                font-size: 14px;
                font-weight: 500;
                > span {
                    margin-right: 5px;
                }
            }
        }
    }

    // 预览图片
    .drap-show-img-box {
        position: fixed;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 99;
        background-color: rgba(0, 0, 0, .5);
        .img-box {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            > img {
                max-width: 100%;
                max-height: 100%;
            }
        }
    }

    // 百度搜索图片
    .baidu-search-box {
        /deep/ .el-dialog__body {
            padding: 0px 20px 20px;
        }
        .baidu-box {
            min-height: 300px;
            .search-box {
                display: flex;
                .baidu-btn {
                    width: 100px;
                    height: 40px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    letter-spacing: 1px;
                    background: #38f;
                    font-size: 14px;
                    color: #ffffff;
                    cursor: pointer;
                }
            }

            .baidu-img-list-box {
                margin-top: 10px;
                max-height: 500px;
                overflow: scroll;
                .baidu-img-list-item {
                    position: relative;
                    float: left;
                    margin-right: 3px;
                    margin-bottom: 3px;
                    border: 1px solid #ffffff;
                    &:hover {
                        .hover-box {
                            opacity: 1;
                        }
                    }
                    &.no-show-img {
                        display: none;
                    }
                    &.img-checked {
                        border-color: #409eff;
                        .check-box {
                            background-color: #409eff;
                        }
                    }
                    .hover-box {
                        opacity: 0;
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        z-index: 1;
                        text-align: right;
                        padding: 10px;
                        width: 100%;
                        height: 35px;
                        background-image:linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, .8));
                        font-size: 14px;
                        color: #ffffff;
                    }
                    .check-box {
                        position: absolute;
                        top: 10px;
                        left: 10px;
                        z-index: 1;
                        width: 12px;
                        height: 12px;
                        border: 1px solid #dcdfe6;
                        background-color: #fff;
                        cursor: pointer;
                        border-radius: 50%;
                        &:hover {
                            border-color: #409eff;
                        }
                    }
                }
            }

            .no-baidu-img {
                min-height: 300px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .baidu-center {
                padding: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
        .baidu-btn-box {
            margin-top: 10px;
            width: 100%;
            display: flex;
            justify-content: flex-end;
        }
    }
</style>
